/*
 * FielAuthorization.java
 *
 * Created on 10 de diciembre de 2005, 15:27
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package org.fiel.filters;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import org.fiel.FielConstants;
import org.fiel.login.FielPrincipal;

/**
 * @author Luis Pablo Gallo (luispablo.gallo@gmail.com)
 */
public class FielAuthorization implements Filter{
    
    public void doFilter( ServletRequest request
                        , ServletResponse response
                        , FilterChain chain )
    throws IOException, ServletException{
        
        if( !this.isAuthorized((HttpServletRequest)request) ){
            request.setAttribute( FielConstants.STRUTS_GLOBAL_ERROR
                                , "Usuario no autorizado para esta operaci\363n." );
        }
        
        chain.doFilter(request, response);
    }
    
    public void init(FilterConfig config) throws ServletException{
    }
    
    public void destroy(){
    }
    
    protected String obtenerRol( HttpServletRequest request ){
        FielPrincipal fielPrincipal = (FielPrincipal)request.getSession().getAttribute("userPrincipal");
        String rol = FielConstants.NIVEL_ACCESO_GENERAL;
        
        if(fielPrincipal != null){
            List ls = fielPrincipal.getRoles();
            
            for(Iterator iter = ls.iterator(); iter.hasNext();){
                rol = rol + (String)iter.next();
            }
        }
        
        return rol;
    }
    
    protected boolean isAuthorized(HttpServletRequest request){
        return obtenerRol(request).indexOf("7") != -1;
    }
    
}
